<template>
    <div class="container">

        <div class="body_wrap">
            <el-card class="body_card" shadow="hover" ref="content_card">
                <div class="header_back_wrap">
                    <el-page-header @back="$router.back(-1)" :content="$route.meta.title" class="headerBack"></el-page-header>
                    <el-divider></el-divider>
                </div>

                <div class="form_content">
                    <div class="table_form_wrap">
                        <el-steps :active="step" finish-status="success" align-center>
                            <el-step title="基本信息"></el-step>
                            <el-step title="商品详情"></el-step>
                            <el-step title="规格属性"></el-step>
                            <el-step title="SKU信息"></el-step>
                            <el-step title="分销设置"></el-step>
                            <el-step title="保存完成"></el-step>
                        </el-steps>
                        <el-divider></el-divider>

                        <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                            <!-- SPU 基本信息 -->
                            <div class="step" v-show="step == 0">
                                <el-form-item label="商品名称" prop="title">
                                    <el-input v-model="form.title" placeholder="" style="width: 80%;"></el-input>
                                </el-form-item>
                                <el-form-item label="商品副标" prop="subTitle">
                                    <el-input v-model="form.subTitle" placeholder="" style="width: 80%;"></el-input>
                                </el-form-item>
                                <el-form-item label="商品分类" prop="cateId">
                                    <CategoryCascader ref="category" :categoryPath.sync="categoryPath"></CategoryCascader>
                                </el-form-item>
                                <el-form-item label="商品品牌" prop="brandId">
                                    <BrandSelect ref="brand" :selectBrandId.sync="selectBrandId"></BrandSelect>
                                </el-form-item>
                                <el-form-item label="商品主图" prop="headImg">
                                    <SingleUpload v-model="form.headImg" listType="picture-card"></SingleUpload>
                                    <i style="color: red" class="mt10">尺寸：150x200</i>
                                </el-form-item>
                                <el-form-item label="商品轮播图" prop="imgs">
                                    <MultiUpload v-model="imgs"></MultiUpload>
                                    <i style="color: red" class="mt10">尺寸：150x200</i>
                                </el-form-item>

                                <el-form-item label="快递运费" prop="freeShippingType">
                                    <el-radio-group v-model="form.freeShippingType">
                                        <div class="freeShipping_wrap">
                                            <el-radio :label="1">
                                                包邮
                                            </el-radio>
                                            <el-radio :label="2">
                                                统一运费
                                                <el-input v-model="form.freeShipping" :disabled="form.freeShippingType!=2" placeholder="" style="width:130px" /> 元
                                            </el-radio>
                                            <!-- <el-radio :label="3">
                                                运费模板
                                                <el-input v-model="form.freeShippingTemplateId" :disabled="form.freeShippingType!=3" placeholder="" style="width:130px" />
                                            </el-radio> -->
                                        </div>
                                    </el-radio-group>
                                </el-form-item>

                                <el-form-item label="库存预警" prop="stockWarn">
                                    <el-input v-model="form.stockWarn" type="number" @input="numberic2(form,'stockWarn',$event)" style="width: 240px;"></el-input>
                                </el-form-item>

                                <el-form-item label="销售状态" prop="status">
                                    <el-radio-group v-model="form.status">
                                        <el-radio :label="1">立即上架</el-radio>
                                        <el-radio :label="2">放入仓库</el-radio>
                                    </el-radio-group>
                                </el-form-item>

                                <div class="foot_submit">
                                    <el-button type="success" @click="handleCollectSpu">下一步：设置商品详情</el-button>
                                </div>
                            </div>

                            <!-- 设置商品详情 -->
                            <div class="step" v-show="step == 1">
                                <div id="decriptEditor"></div>

                                <div class="foot_submit">
                                    <el-button type="primary" @click="step = 0">上一步</el-button>
                                    <el-button type="success" @click="handleCollectSpuDetail">下一步：设置规格属性</el-button>
                                </div>
                            </div>

                            <!-- 设置规格属性 -->
                            <div class="step" v-show="step == 2">

                                <el-card class="box-card"  v-if="attrGroups && attrGroups.length > 0">

                                    <el-tabs tab-position="left" style="width:98%; margin-bottom: 20px">
                                        <el-tab-pane
                                        :label="group.attrGroupName"
                                        v-for="(group, gidx) in attrGroups"
                                        :key="group.attrGroupId">

                                            <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  form.baseAttrs[0] = [{attrId:xx,val:}]-->
                                            <el-form :model="form">
                                                <el-form-item v-for="(attr,aidx) in group.attrs" :key="attr.id">
                                                    <div class="base_attr_wrap">
                                                        <div class="label">
                                                            {{attr.attrName}}
                                                        </div>
                                                        <div class="select_vals">
                                                            <el-select
                                                                v-model="dataResp.baseAttrs[gidx][aidx].attrValues"
                                                                :multiple="attr.valueType == 1"
                                                                filterable
                                                                allow-create
                                                                default-first-option
                                                                placeholder="请选择或输入值"
                                                                style="width: 100%">
                                                                    <el-option
                                                                        v-for="(val,vidx) in attr.valueSelect.split(';')"
                                                                        :key="vidx"
                                                                        :label="val"
                                                                        :value="val">
                                                                    </el-option>
                                                            </el-select>
                                                        </div>
                                                        <div class="show_desc">
                                                            <el-checkbox
                                                                v-model="dataResp.baseAttrs[gidx][aidx].showDesc"
                                                                :true-label="1"
                                                                :false-label="0"
                                                            >快速展示</el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-form-item>
                                            </el-form>
                                            <el-button type="primary">添加属性</el-button>
                                        </el-tab-pane>
                                    </el-tabs>

                                </el-card>

                                <el-alert v-else title="提示" type="warning" description="该商品分类，无规格参数信息" show-icon />

                                <div class="foot_submit mt10">
                                    <el-button type="primary" @click="step = 1">上一步</el-button>
                                    <el-button type="success" @click="generateSaleAttrs">下一步：设置SKU信息</el-button>
                                </div>
                            </div>

                            <!-- 设置SKU信息，并保存商品信息 -->
                            <div class="step" v-show="step == 3">
                                <el-card shadow="hover" ref="content_card">
                                    <el-radio-group v-model="form.specType" style="margin: 8px 0;">
                                        <el-radio :label="1">统一规格</el-radio>
                                        <el-radio :label="2">多规格</el-radio>
                                    </el-radio-group>
                                    <el-button v-if="form.specType == 2" style="margin-left:20px" @click="handleAddSaleAttr" type="primary" size="mini" icon="el-icon-plus">添加规格</el-button>
                                </el-card>

                                <!-- 统一规格 -->
                                <el-card shadow="hover" ref="content_card" class="mt10" v-show="form.specType == 1">
                                    <el-table :data="skus1" fit border class="mt10">
                                        <el-table-column label="规格图片" width="100" align="center">
                                            <template slot-scope="scope">
                                                <div class="skuImg">
                                                    <SingleUpload v-model="scope.row.skuImg" listType="picture-card"></SingleUpload>
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="SKU名称">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.skuName"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="销售价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.salePrice"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="成本价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.costPrice"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="市场价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.marketPrice"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="库存" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.stockNum"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="条码" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.barcode"></el-input>
                                            </template>
                                        </el-table-column>
                                    </el-table>

                                </el-card>

                                <!-- 多规格 -->
                                <el-card shadow="hover" ref="content_card" class="mt10" v-show="form.specType == 2">

                                    <el-divider content-position="left"><b>销售规格</b></el-divider>
                                    <!-- 规格设置 -->
                                    <el-table :data="tableSaleAttrs" fit :border="false" :show-header="false" empty-text="暂无数据，请添加规格">
                                        <el-table-column label="规格项" width="200px">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.attrName" size="medium" @blur="generateSkus"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="规格值">
                                            <template slot-scope="scope">
                                                <el-checkbox-group v-model="tableSaleAttrs[scope.$index].attrValues" @change="generateSkus">

                                                    <template v-if="tableSaleAttrs[scope.$index].valueSelect">
                                                        <el-checkbox
                                                        :label="val"
                                                        v-for="val in tableSaleAttrs[scope.$index].valueSelect.split(';')"
                                                        :key="val"
                                                        style="margin-right: 20px;"
                                                        ></el-checkbox>
                                                    </template>

                                                    <div style="display:inline">
                                                        <el-button
                                                            v-show="!inputVisible[scope.$index].view"
                                                            class="button-new-tag"
                                                            size="medium"
                                                            icon="el-icon-plus"
                                                            @click="showInput(scope.$index)">自定义</el-button>
                                                        <el-input
                                                            v-show="inputVisible[scope.$index].view"
                                                            v-model="inputValue[scope.$index].val"
                                                            :ref="`SpecInputValue`"
                                                            size="medium"
                                                            style="width:150px"
                                                            @keyup.enter.native="handleInputConfirm(scope.$index)"
                                                            @blur="handleInputConfirm(scope.$index)"
                                                        ></el-input>
                                                    </div>
                                                </el-checkbox-group>
                                            </template>
                                        </el-table-column>
                                    </el-table>

                                    <el-divider content-position="left"><b>SKU列表</b></el-divider>

                                    <div class="batch" v-if="form.specType == 2 && skus2 && skus2.length > 0">
                                        <div class="title">批量设置</div>
                                        <el-input placeholder="SKU名称" v-model="batch.skuName" style="width: 250px;margin-left:10px"></el-input>
                                        <el-input placeholder="销售价(元)" type="number" v-model="batch.salePrice" @input="numberic(batch, 'salePrice', $event)" style="width: 100px;margin-left:10px"></el-input>
                                        <el-input placeholder="成本价(元)" type="number" v-model="batch.costPrice" @input="numberic(batch, 'costPrice', $event)" style="width: 100px;margin-left:10px"></el-input>
                                        <el-input placeholder="市场价(元)" type="number" v-model="batch.marketPrice" @input="numberic(batch, 'marketPrice', $event)" style="width: 100px;margin-left:10px"></el-input>
                                        <el-input placeholder="库存量" type="number" v-model="batch.stockNum" @input="numberic2(batch, 'stockNum', $event)" style="width: 100px;margin-left:10px"></el-input>
                                        <el-input placeholder="条形码" v-model="batch.barcode" style="width: 150px;margin-left:10px"></el-input>
                                        <el-button @click="handleBatchInput" type="primary" style="margin-left:10px">确认</el-button>
                                    </div>

                                    <!-- SKU销售数据组合 -->
                                    <el-table :data="skus2" height="500" fit border class="mt10" empty-text="暂无数据，请先添加销售规格">

                                        <el-table-column :label="`属性组合 （${skus2?skus2.length:0}个SKU）`">
                                            <el-table-column
                                                :label="item.attrName"
                                                v-for="(item, index) in skuAttrTableColumn"
                                                :key="index"
                                            >
                                                <template slot-scope="scope" v-if="scope.row.specAttrs[index]">
                                                    <span style="margin-left: 10px">{{
                                                        scope.row.specAttrs[index].attrValue
                                                    }}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column label="规格图片" width="100" align="center">
                                            <template slot-scope="scope">
                                                <div class="skuImg">
                                                    <SingleUpload v-model="scope.row.skuImg" listType="picture-card"></SingleUpload>
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="SKU名称" width="200">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.skuName"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="销售价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.salePrice" type="number" @input="numberic(scope.row,'salePrice',$event)"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="成本价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.costPrice" type="number" @input="numberic(scope.row,'costPrice',$event)"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="市场价(元)" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.marketPrice" type="number" @input="numberic(scope.row,'marketPrice',$event)"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="库存" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.stockNum" type="number" @input="numberic2(scope.row,'stockNum',$event)"></el-input>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="条码" width="150">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.barcode"></el-input>
                                            </template>
                                        </el-table-column>

                                    </el-table>

                                </el-card>

                                <div class="foot_submit mt10">
                                    <el-button type="primary" @click="handleCollectSpuDetail">上一步</el-button>
                                    <el-button type="success" @click="handleCommission">下一步：设置分销</el-button>
                                </div>
                            </div>

                            <!-- 分销设置 -->
                            <div class="step" v-show="step == 4">

                                <el-form-item label="分销佣金" prop="isCommission">
                                    <el-radio-group v-model="form.isCommission">
                                        <el-radio :label="1">开启</el-radio>
                                        <el-radio :label="2">不开启</el-radio>
                                    </el-radio-group>
                                </el-form-item>

                                <el-form-item label="一级分销比例" prop="firstRatio">
                                    <el-input v-model="form.firstRatio" placeholder="" type="number" @input="numberic100(form,'firstRatio',$event)" style="width:200px"></el-input>
                                </el-form-item>
                                <el-form-item label="二级分销比例" prop="secondRatio">
                                    <el-input v-model="form.secondRatio" placeholder="" type="number" @input="numberic100(form,'secondRatio',$event)" style="width:200px"></el-input>
                                </el-form-item>
                                <el-form-item label="三级分销比例" prop="threeRatio">
                                    <el-input v-model="form.threeRatio" placeholder="" type="number" @input="numberic100(form,'threeRatio',$event)" style="width:200px"></el-input>
                                </el-form-item>


                                <div class="foot_submit mt10">
                                    <el-button type="primary" @click="step = 3">上一步</el-button>
                                    <el-button type="success" @click="handleSubmit">下一步：保存商品信息</el-button>
                                </div>
                            </div>


                            <!-- 保存成功 -->
                            <div class="step" v-show="step == 5">
                                <el-card class="box-card">
                                    <div class="success">
                                        <i class="el-icon-circle-check"></i>
                                        <el-button type="primary" @click="handleSuccess">提交成功，返回商品列表</el-button>
                                    </div>
                                </el-card>
                            </div>


                        </el-form>
                    </div>
                </div>


            </el-card>
        </div>

    </div>
</template>

<script>
import CategoryCascader from "@/views/mall/pmscategory/components/category-cascader";
import BrandSelect from "@/views/mall/pmsbrand/components/brand-select";
import SingleUpload from '@/views/components/upload/single-upload'
import MultiUpload from "@/views/components/oss/upload/MultipartUpload";
import E from "wangeditor";
import Config from '@/config'
var OSS = require('ali-oss');
import { getUUID, numberic, numberic2, numberic100 } from "@/libs";

export default {
    components: {
        CategoryCascader,
        BrandSelect,
        SingleUpload,
        MultiUpload
    },
    data() {
        return {
            catePathSub: null,
            brandIdSub: null,
            step: 3,
            submitLoading: false,
            form: {
                cateId: null,
                brandId: null,
                title: null,
                subTitle: null,
                imgs: [],
                decript: null,
                newRecommend: null,
                isCommission: 2,
                firstRatio: null,
                secondRatio: null,
                threeRatio: null,
                stockWarn: null,
                freeShippingType: 1,
                freeShipping: null,
                freeShippingTemplateId: null,
                status: 1,
                specType: 2,        // 规格类型：1->统一规格，2->多规格
                baseAttrs: [],      // 基本属性
                skus: [],           // 所有sku信息
                spuAttrValues: []   // 服务器返回的基本规格属性
            },
            rules: {
                cateId: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ],
                title: [
                    { required: true, message: '标题不能为空', trigger: 'blur' }
                ]
            },
            // 商品轮播图
            imgs: [],

            categoryPath: [],
            selectBrandId: null,

            clinet: null,
            decriptEditor: null,
            decriptContent: null,

            // 属性分组
            attrGroups: [],
            dataResp: {
                baseAttrs: [],
            },

            // 规格设置
            tableSaleAttrs: [],
            inputVisible: [],
            inputValue: [],

            // SKU 销售属性表格头
            skuAttrTableColumn: [],

            // 统一规格
            skus1: [{
                // SKU基本信息
                skuName: null,
                skuImg: null,
                salePrice: 0,
                marketPrice: 0,
                costPrice: 0,
                stockNum: 0,
                barcode: null
            }],
            // 多规格
            skus2: [],

            // 批量设置价格参数
            batch: {
                skuName: null,
                salePrice: null,
                marketPrice: null,
                costPrice: null,
                stockNum: null,
                barcode: null
            },

            numberic,
            numberic2,
            numberic100
        }
    },

    created() {
        this.form.id = this.$route.query.id
    },

    mounted() {
        this.$nextTick(() => {
            this.initEditor()

            // 订阅消息，当分类级联发生变动，级联组件发布订阅消息，获取分类ID
            this.catePathSub = PubSub.subscribe("catePathId", (msg, val) => {
                if(val.length > 0) {
                    this.form.cateId = val[val.length - 1];
                }
            });
            // 订阅消息，品牌组件发布订阅消息，获取品牌ID
            this.brandIdSub = PubSub.subscribe("brandId", (msg, val) => {
                this.form.brandId = val;
            });

            if(this.form.id) {
                this.getInfo(this.form.id)
            }


            // 测试SKU用的数据
            let attrs = [
                {
                    attrId: 0,
                    attrName: '颜色',
                    attrValues: [],
                    valueSelect: "白色;红色;蓝色"
                },
                {
                    attrId: 1,
                    attrName: '内存',
                    attrValues: [],
                    valueSelect: "8G;16G;32G"
                }
            ]
            this.tableSaleAttrs = attrs
            this.inputVisible = [{ view: false }, { view: false }];
            this.inputValue = [{ val: "" }, { val: "" }];
        })
    },

    methods: {


        /**
         * 第1步
         * SPU基本信息录入
         * 验证成功则跳转到第2步：设置商品详情
         */
        handleCollectSpu() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.step = 1;
                } else {
                    return false;
                }
            });
        },

        /**
         * 第2步
         * 跳转到第3步：设置规格属性
         */
        handleCollectSpuDetail() {
            this.step = 2;
            this.showBaseAttrs()
        },

        /**
         * 根据分类获取规格属性
         */
        async showBaseAttrs() {
            const res = await this.$http({
                url: `/mall/pmsattrgroup/${this.form.cateId}/withattr`,
                method: 'GET'
            })
            if (this.ResultMessage(res, false)) {
                let list = res.data
                if(list && list.length > 0) {
                    //先对表单的baseAttrs进行初始化
                    list.forEach(item => {
                        let attrArray = [];

                        if(item.attrs) {
                            item.attrs.forEach(attr => {
                                if(this.form.spuAttrValues && this.form.spuAttrValues.length > 0) {
                                    // 回填基本规格属性
                                    let val = this.form.spuAttrValues.filter(item => item.attrId == attr.id)
                                    if(val && val.length > 0) {
                                        const baseAttr = val[0]
                                        attrArray.push({
                                            attrId: attr.id,
                                            attrValues: baseAttr.valueType == 0 ? baseAttr.attrValue : baseAttr.attrValue.split(';'),
                                            showDesc: attr.showDesc
                                        });
                                    } else {
                                        attrArray.push({
                                            attrId: attr.id,
                                            attrValues: "",
                                            showDesc: attr.showDesc
                                        });
                                    }
                                } else {
                                    attrArray.push({
                                        attrId: attr.id,
                                        attrValues: "",
                                        showDesc: attr.showDesc
                                    });
                                }
                            });
                            this.dataResp.baseAttrs.push(attrArray);
                        } else {
                            this.dataResp.baseAttrs.push([]);
                        }
                    });
                    this.attrGroups = list;

                } else {
                    this.dataResp.baseAttrs = []
                    this.attrGroups = []
                }
            }
        },

        /**
         * 第3步
         * 把页面绑定的所有“规格属性”处理到form的baseAttr里
         * 跳转到第4步：设置SKU
         */
        generateSaleAttrs() {
            this.form.baseAttrs = [];
            this.dataResp.baseAttrs.forEach(item => {
                item.forEach(attr => {
                    let { attrId, attrValues, showDesc } = attr;
                    //跳过没有录入值的属性
                    if (attrValues != "") {
                        if (attrValues instanceof Array) {
                            //多个值用;隔开
                            attrValues = attrValues.join(";");
                        }
                        this.form.baseAttrs.push({ attrId, attrValues, showDesc });
                    }
                });
            });
            this.step = 3;
        },

        /**
         * 第4步
         * 完成SKU相关设置，点击下一步提交表单
         * 跳转到第5步：表单提交完成/失败
         */
        /**
         * SKU销售规格相关设置
         */
        handleAddSaleAttr() {
            let attr = {
                attrId: null,
                attrName: null,
                attrValues: [],
                valueSelect: ''
            }
            this.tableSaleAttrs.push(attr)
            this.tableSaleAttrs.forEach((item, index) => item.attrId = index)
            this.inputVisible.push({ view: false });
            this.inputValue.push({ val: "" });
        },
        showInput(idx) {
            this.inputVisible[idx].view = true;
            this.$nextTick(() => this.$refs.SpecInputValue.focus());
        },
        handleInputConfirm(idx) {
            let inputValue = this.inputValue[idx].val;
            if (inputValue) {
                if (!this.tableSaleAttrs[idx].valueSelect || this.tableSaleAttrs[idx].valueSelect == "") {
                    this.tableSaleAttrs[idx].valueSelect = inputValue;
                } else {
                    this.tableSaleAttrs[idx].valueSelect += ";" + inputValue;
                }
            }
            this.inputVisible[idx].view = false;
            this.inputValue[idx].val = "";
        },

        /**
         * 生成SKU信息
         */
        generateSkus() {
            // 选中的规格
            let selectValues = [];
            // SKU销售属性的列名称
            this.skuAttrTableColumn = []

            this.tableSaleAttrs.forEach(item => {
                if(item.attrName && item.attrValues.length > 0) {
                    // 收集销售属性值，进行笛卡尔积运算生成SKU组合
                    selectValues.push(item.attrValues);
                    // 销售属性列名称
                    this.skuAttrTableColumn.push(item);
                }
            });

            //根据笛卡尔积运算进行生成sku组合
            let descartes = this.descartes(selectValues);
            console.log("SKU生成的组合", JSON.stringify(descartes));

            //有多少descartes就有多少sku
            let skus = [];
            descartes.forEach((descar, descaridx) => {
                let attrArray = []; //sku属性组

                descar.forEach((de, index) => {
                    //构造saleAttr信息
                    let saleAttrItem = {
                        attrId: this.skuAttrTableColumn[index].attrId,
                        attrName: this.skuAttrTableColumn[index].attrName,
                        attrValue: de
                    };
                    attrArray.push(saleAttrItem);
                });

                // 判断如果之前有就用之前的值;
                let res = this.hasAndReturnSku(this.skus2, descar);

                if (res === null) {
                    skus.push({
                        // 销售属性
                        specAttrs: attrArray,
                        // 销售规格
                        specDescar: descar,
                        // SKU基本信息
                        skuName: this.form.title + " " + descar.join(" "),
                        skuImg: null,
                        salePrice: 0,
                        marketPrice: 0,
                        costPrice: 0,
                        stockNum: 0,
                        barcode: null
                    });
                } else {
                    skus.push(res);
                }

            })

            // SKU销售属性组合列表
            this.skus2 = skus;

            // this.skus2.forEach((item, index) => {
            //     console.log(JSON.stringify(item));
            // })
        },

        /**
         * 回填SKU销售规格信息
         */
        handleSkuAttr(skus) {
            let map = new Map();
            skus.forEach((item, index) => {
                if(item.specAttrs) {
                    item.specAttrs.forEach(ia => {
                        let val = map.get(ia.attrName);
                        if(val) {
                            let vals = val.split(';')
                            if(vals.indexOf(ia.attrValue) == -1) {
                                map.set(ia.attrName, vals.join(';') + ';' + ia.attrValue)
                            }
                        } else {
                            map.set(ia.attrName, ia.attrValue)
                        }
                    })
                }
            })

            let attrs = []
            map.forEach((value, key, Map) => {
                attrs.push(
                    {
                        attrId: 0,
                        attrName: key,
                        attrValues: value.split(';'),
                        valueSelect: value
                    }
                )
                this.inputVisible.push({ view: false });
                this.inputValue.push({ val: "" });
            })
            this.tableSaleAttrs = attrs
            this.generateSkus()
        },



        /**
         * 第4步
         * 分销设置，点击下一步提交表单
         * 跳转到第5步：表单提交完成/失败
         */
        handleCommission() {

            this.step = 4;
        },

        /**
         * 提交表单
         */
        async handleSubmit() {
            const refs = this.$refs
            this.submitLoading = true
            const valid = await refs['form'].validate().catch(() => {})
            if(valid) {

                // 商品轮播图
                if(this.imgs) {
                    let imgList = []
                    this.imgs.forEach((item, index) => {
                        imgList.push({imgName: item.name, imgUrl: item.url})
                    })
                    this.form.imgs = imgList
                }

                // 统一规格
                if(this.form.specType == 1) {
                    this.form.skus = this.skus1
                } else {
                    // 多规格
                    this.form.skus = this.skus2
                }

                const confirm = await this.$confirm('将要提交商品数据，需要一小段时间，是否继续?', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: `/mall/pmsspu/${!this.form.id ? 'saveGoodsInfo' : 'updateGoodsInfo'}`,
                        method: 'POST',
                        data: this.form
                    })
                    if (this.ResultMessage(res)) {
                        this.form.skus = []
                        this.step = 5;
                        this.submitLoading = false
                    } else {
                        this.submitLoading = false
                    }
                }
            } else {
                this.submitLoading = false
            }
        },

        /**
         * 第6步：完成提交，显示相关成功或失败信息
         */
        handleSuccess() {
            this.$router.back(-1)
        },



        /**
         * 获取SPU详细信息
         */
        async getInfo(id) {
            if (id) {
                const res = await this.$http({
                    url: '/mall/pmsspu/getGoodsInfo/',
                    method: 'GET',
                    params: {id}
                })
                this.form = Object.assign({}, res.data)

                this.categoryPath = this.form.categoryPath
                this.selectBrandId = this.form.brandId

                this.decriptEditor.txt.html(this.form.decript)

                this.form.imgs.forEach((item, index) => {
                    this.imgs.push({name: item.imgName, url: item.imgUrl})
                })

                // 统一规格
                if(this.form.specType == 1) {
                    this.skus1 = this.form.skus
                } else {
                    // 多规格

                    this.form.skus.forEach((item, index) => {
                        let attrs = JSON.parse(item.attrs)
                        let descar = JSON.parse(item.descar)
                        item['specAttrs'] = attrs
                        item['specDescar'] = descar
                    })

                     // 初始化销售规格
                    this.skus2 = this.form.skus
                    this.handleSkuAttr(this.form.skus)

                    // 批量设置：初始化skuName
                    this.batch.skuName = this.form.title
                }
            }
        },

        /**
         * 批量设置
         */
        handleBatchInput() {
            this.skus2.forEach(item => {
                item.skuName = this.batch.skuName ? this.batch.skuName : item.skuName
                item.salePrice = this.batch.salePrice ? this.batch.salePrice : item.salePrice
                item.costPrice = this.batch.costPrice ? this.batch.costPrice : item.costPrice
                item.marketPrice = this.batch.marketPrice ? this.batch.marketPrice : item.marketPrice
                item.stockNum = this.batch.stockNum ? this.batch.stockNum : item.stockNum
                item.barcode = this.batch.barcode ? this.batch.barcode : item.barcode
            })
        },

        /**
         * 笛卡尔积运算，生成SKU销售组合
         */
        descartes(list) {
            //parent上一级索引;count指针计数
            var point = {};

            var result = [];
            var pIndex = null;
            var tempCount = 0;
            var temp = [];

            //根据参数列生成指针对象
            for (var index in list) {
                if (typeof list[index] == "object") {
                    point[index] = { parent: pIndex, count: 0 };
                    pIndex = index;
                }
            }

            //单维度数据结构直接返回
            if (pIndex == null) {
                return list;
            }

            //动态生成笛卡尔积
            while (true) {
                for (var index in list) {
                    tempCount = point[index]["count"];
                    temp.push(list[index][tempCount]);
                }

                //压入结果数组
                result.push(temp);
                temp = [];

                //检查指针最大值问题
                while (true) {
                    if (point[index]["count"] + 1 >= list[index].length) {
                        point[index]["count"] = 0;
                        pIndex = point[index]["parent"];
                        if (pIndex == null) {
                            return result;
                        }

                        //赋值parent进行再次检查
                        index = pIndex;
                    } else {
                        point[index]["count"]++;
                        break;
                    }
                }
            }
        },

        /**
         * 判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
         */
        hasAndReturnSku(skus, descar) {
            let res = null;
            if (skus && skus.length > 0) {
                for (let i = 0; i < skus.length; i++) {
                    if(skus[i].specDescar) {
                        if (skus[i].specDescar.join(" ") == descar.join(" ")) {
                            res = skus[i];
                        }
                    }
                }
            }
            return res;
        },

        /**
         * 初始化编辑器
         */
        async initEditor() {
            const _this = this
            // 初始化阿里云OSS
            this.clinet = new OSS(Config.Aliyun.oss);

            const decriptEditor = new E('#decriptEditor')
            decriptEditor.config.showFullScreen = false
            decriptEditor.config.height = 500
            decriptEditor.config.zIndex = 1
            decriptEditor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
            decriptEditor.config.uploadVideoAccept = ['mp4']

            // 自定义上传图片
            decriptEditor.config.customUploadImg = async function (resultFiles, insertImgFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertImgFn)

                _this.loading.close()
            }
            // 自定义上传视频
            decriptEditor.config.customUploadVideo = async function (resultFiles, insertVideoFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertVideoFn)

                _this.loading.close()
            }
            // 配置 onchange 回调函数，将数据同步到 vue 中
            decriptEditor.config.onchange = (newHtml) => {
                _this.form.decript = newHtml
            }
            decriptEditor.create()

            this.decriptEditor = decriptEditor
        },
        /**
         * 上传到阿里云OSS
         */
        async handleUpload(resultFiles, insert) {
            const _this = this
            for(const file of resultFiles) {
                try {
                    let result = await this.clinet.multipartUpload(getUUID(), file, {
                        progress(p, checkpoint) {
                            // console.log('Object的上传进度', p);
                            // console.log('分片上传的断点信息', checkpoint);
                            _this.progress = p
                        }
                    })
                    const url = result.res.requestUrls[0].split('?')[0]
                    insert(url)
                } catch(err) {
                    console.log(err);
                }
            }
        },

        /**
         * 只允许输入金额数字
         * type 为number
         * item 为json对象
         * keyname为键值
         * event为事件对象.两位小数
         */
        numberic:function(item, keyname, event){
            var value=item[keyname];
            var zeroFirst=value.indexOf(0);
            var dot=value.indexOf('.');
            var vlen=value.length

            if(value.indexOf('.')==0){
                // alert("value.indexOf('.'):"+value.indexOf('.'));
                // alert("请输入合法的数字!");
                item[keyname]=0;
            }
            if(zeroFirst==0){//首位为0,第二位则必须为.
                if(vlen>=3 && value.indexOf('.')==1){
                    if(value.length>4){
                        item[keyname]=value.substr(0,vlen-1);
                        // alert("最多两位小数!");
                    }else{
                        if(isNaN(Number(value[vlen-1]))){
                            item[keyname]=value.substr(0,vlen-1);
                            // alert("请输入合法的数字!");
                        }
                    }
                }else if(vlen==2 && value.indexOf('.')!=1){
                    // alert("请输入小数点！");
                    item[keyname]=0;
                }
            }else{
                if(dot>-1 && dot+1!=vlen){//已输入小数点
                    if(isNaN(Number(value[vlen-1]))){//小数点后只能输入0-9
                        item[keyname]=value.substr(0,vlen-1);
                        // alert("请输入合法的数字0-9!");
                    }else if(vlen-dot>2+1){
                        item[keyname]=value.substr(0,vlen-1);
                    }
                }else if(dot==-1){

                }
            }
        },

        // 整数，非0开头
        numberic2(item, keyname, event) {
            var value=item[keyname];
            var reg=/^[1-9]\d*$/ ;
            if(!value.match(reg)){
                item[keyname] = ''
            } else {
                item[keyname] = value
            }
        },

        numberic100(item, keyname, event) {
            var value=item[keyname];
            var reg=/^([1-9][0-9]{0,1}|100)$/ ;
            if(!value.match(reg)){
                let num = Number(value)
                if(num > 100) {
                    item[keyname] = 100
                } else {
                    item[keyname] = ''
                }
            } else {
                item[keyname] = value
            }
        }
    }
}
</script>
<style lang="scss">
.skuImg{
    display: flex;
    justify-content: center;
    align-items: center;
    .el-upload--picture-card{
        width: 60px;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .el-upload-list--picture-card .el-upload-list__item{
        margin: 0;
        width: 60px;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .disabled .el-upload--picture-card, .disabled .el-upload--picture{
        display: none;
    }
}
</style>
<style lang="scss" scoped>
.success {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 100px 0;
    i{
        font-size: 100px;
        color: #67C23A;
        margin-bottom: 20px;
        margin-bottom: 100px;
    }
}

#decriptEditor{
    margin-bottom: 20px;
}

.batch{
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
.base_attr_wrap{
    display: flex;
    .label{
        flex: 1;
    }
    .select_vals {
        display: flex;
        justify-content: flex-start;
        flex: 8;

    }
    .show_desc {
        display: flex;
        justify-content: flex-start;
        flex: 1;
        margin-left: 10px;
    }
}

.freeShipping_wrap{
    display: flex;
    flex-direction: column;

    &:first-child {
        margin-top: 13px;
    }

    .el-radio{
        margin-bottom: 10px;

        .el-input{
            margin-left: 20px;
            margin-right: 10px;
        }
    }
}
</style>
